<?php
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');

$sSql = "SELECT sd.* "
	." FROM rgl_set_dati sd "
	." WHERE sd.id_set_dati = ".reqVarInt('sd');
$objDB->query($sSql, 'readBil');
$aRec = $objDB->fetch('readBil');
if (!$aRec) {
	die('no bil. '.reqVarAS('ca')."/".reqVarAS('dr'));
}

$aTTD = array(1=>'Bilancio UE');
$aTTD[2] = 'Bilancio riclassificato';
$aTTD[3] = 'Rendiconto finanziario';
$aTTD[11] = $aRec['indici1'];
$aTTD[12] = $aRec['indici2'];
$aTTD[13] = $aRec['indici3'];

$aGeDati = getGerarcTabDati(reqvar('sd'),reqvar('ttd'));
//dbg_($aGeDati);
//dbg_($aDati);
$sCsv = '"liv";"codice";"descrizione";"seq";"tipo";"quad";"script"'."\r\n";
foreach($aGeDati as $codX => $aX) {
	genCsvDat($sCsv,$codX,$aX,0);
}
headerDownLoad(strlen($sCsv),"tab_dati_".$aRec['cod_set_dati']."_".reqvar('ttd').".csv");
echo $sCsv;
exit();


function genCsvDat(&$sCsv,$codX, $aX, $liv) {
	global $objDB,$objSess;
	$sSql = "SELECT d.* "
		." FROM rgl_def_dato d "
		." WHERE d.cod_dato = '$codX'"
		;
	$objDB->query($sSql, 'readDato');
	$acD = $objDB->fetch('readDato');
	$sCsv .= '"'.$liv.'"';
	$sCsv .= ';"'.$codX.'"';
	$sCsv .= ';"'.zzRep($acD['descr']).'"';
	$sCsv .= ';"'.zzRep($acD['seq']).'"';
	$sCsv .= ';"'.zzRep($acD['tipo_valore']).'"';
	$sCsv .= ';"'.zzRep($acD['flag_quad_calc']).'"';
	$sCsv .= ';"'.zzRep($acD['script']).'"';
	$sCsv .= "\r\n";
	foreach($aX['figli'] as $codY => $aY)  {
		genCsvDat($sCsv,$codY, $aY, $liv+1);
	}
}

function zzRep($x) {
	$x = str_replace('"',"'",$x);
	$x = str_replace("\n","",$x);
	return $x;
}